package com.zhike.api.controller.system;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.agora.media.RtcTokenBuilder2;
import io.agora.media.RtcTokenBuilder2.Role;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zhike.common.dto.AgoraDTO;
import com.zhike.common.dto.R;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.service.system.ISystemService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("api/zkim/sys")
@Api(tags = "声网")
@Slf4j
public class ShengwangController {

    @Value("${agora.appId}")
    private String appId;

    @Value("${agora.appSecret}")
    private String appSecret;

    static int tokenExpirationInSeconds = 3600;
    static int privilegeExpirationInSeconds = 3600;

    @Autowired
    private ISystemService systemService;

    @ApiOperation(value = "获取声网1v1配置")
    @PostMapping("getAgoraProperty")
    public R<Boolean> getAgoraProperty(@Validated @RequestBody AgoraDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        String channelName = StringUtils.isBlank(dto.getChannelName()) ? IdWorker.getId() + "" : dto.getChannelName();

        RtcTokenBuilder2 token = new RtcTokenBuilder2();
        String result = token.buildTokenWithUserAccount(appId, appSecret, channelName, uc.getFakeUid(),
                Role.ROLE_PUBLISHER,
                tokenExpirationInSeconds, privilegeExpirationInSeconds);

        log.info("shengwang Token: {}", result);
        return R.success(result);
    }
}
